<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <img src="@/assets/airline-logo.png" alt="航空公司Logo" class="logo">
        <h1>天津滨海机场航班分析及管理平台</h1>
        <p class="subtitle">注册新账号</p>
      </div>

      <el-form
        ref="registerForm"
        :model="form"
        :rules="rules"
        label-position="top"
        class="register-form"
        @submit.prevent="handleSubmit"
      >
        <div class="form-grid">
          <el-form-item label="用户名" prop="username" class="form-item">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              size="medium"
            >
              <template #prefix>
                <el-icon class="input-icon"><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email" class="form-item">
            <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
              size="medium"
            >
              <template #prefix>
                <el-icon class="input-icon"><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="电话" prop="phone" class="form-item">
            <el-input
              v-model="form.phone"
              placeholder="请输入电话"
              size="medium"
            >
              <template #prefix>
                <el-icon class="input-icon"><Iphone /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="性别" prop="gender" class="form-item">
            <el-select
              v-model="form.gender"
              placeholder="请选择性别"
              size="medium"
              style="width: 100%"
            >
              <el-option label="男" value="M" />
              <el-option label="女" value="F" />
              <el-option label="未知" value="U" />
            </el-select>
          </el-form-item>

          <el-form-item label="密码" prop="password" class="form-item">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
              show-password
              size="medium"
            >
              <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword" class="form-item">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请确认密码"
              show-password
              size="medium"
            >
              <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>

        <el-form-item prop="agreed" class="agreement-item">
          <el-checkbox v-model="form.agreed" size="small">
            我已阅读并同意
            <el-link type="primary" @click="showAgreement = true">《用户协议》</el-link>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            size="medium"
            :loading="loading"
            class="register-btn"
          >
            立即注册
          </el-button>
        </el-form-item>
      </el-form>

      <div class="register-footer">
        <p>已有账号？<el-link type="primary" @click="$router.push('/login')">立即登录</el-link></p>
      </div>
    </div>

    <el-dialog v-model="showAgreement" title="用户协议" width="50%">
      <div class="agreement-content">
        <h3>天津滨海机场航班分析及管理平台用户协议</h3>
        <p>1. 用户在使用本平台服务前，请务必仔细阅读并理解本协议的全部内容。</p>
        <p>2. 用户应保证提供的账号信息真实、准确、完整，并及时更新。</p>
        <p>3. 用户不得将账号转让或出借给他人使用，否则应承担由此产生的全部责任。</p>
        <p>4. 用户应妥善保管账号及密码安全，对通过账号进行的操作承担法律责任。</p>
        <p>5. 本平台有权根据业务需要调整服务内容，并保留随时修改本协议的权利。</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="showAgreement = false">我已阅读</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register, checkEmail } from '@/api/auth'
import { User, Message, Lock, Iphone } from '@element-plus/icons-vue'

const router = useRouter()

const form = ref({
  username: '',
  email: '',
  phone: '',
  gender: 'U',
  password: '',
  confirmPassword: '',
  agreed: false
})

const validatePass2 = (rule, value, callback) => {
  if (value !== form.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validateEmail = async (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入邮箱地址'))
    return
  }

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
    return
  }

  try {
    const response = await checkEmail(value)
    if (response.exists) {
      callback(new Error('该邮箱已被注册'))
    } else {
      callback()
    }
  } catch (error) {
    callback(new Error('邮箱验证失败'))
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  agreed: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户协议'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const registerForm = ref(null)
const loading = ref(false)
const showAgreement = ref(false)

const handleSubmit = async () => {
  try {
    // 验证表单
    await registerForm.value.validate()

    loading.value = true
    const response = await register({
      username: form.value.username,
      email: form.value.email,
      phone: form.value.phone,
      gender: form.value.gender,
      password: form.value.password
    })

    if (response.status === 'success') {
      ElMessage.success(response.message)
      router.push('/login')
    } else {
      // 处理特定字段错误
      if (response.field === 'email') {
        registerForm.value.validateField('email', () => {})
      } else if (response.field === 'username') {
        registerForm.value.validateField('username', () => {})
      }
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error.response) {
      const errorData = error.response.data
      if (errorData.field) {
        registerForm.value.validateField(errorData.field, () => {})
      }
      ElMessage.error(errorData.message || '注册失败')
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}
</script>
<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('@/assets/airport-bg.jpg') no-repeat center center;
  background-size: cover;
  position: relative;
  padding: 15px;
}

.register-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 0;
}

.register-box {
  width: 100%;
  max-width: 420px;
  padding: 25px;
  background: rgba(255, 255, 255, 0.96);
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.logo {
  height: 45px;
  margin-bottom: 15px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.register-header {
  text-align: center;
  margin-bottom: 20px;
}

.register-header h1 {
  font-size: 20px;
  margin-bottom: 6px;
  color: #333;
  font-weight: 600;
}

.subtitle {
  font-size: 14px;
  color: #666;
}

.register-form {
  margin-top: 15px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
}

.form-item {
  margin-bottom: 0;
}

.form-item :deep(.el-form-item__label) {
  padding-bottom: 5px;
  font-size: 13px;
  line-height: 1.2;
}

.agreement-item {
  margin: 15px 0 18px;
}

.agreement-item :deep(.el-checkbox__label) {
  font-size: 13px;
}

.register-btn {
  width: 100%;
  margin-top: 10px;
  font-size: 14px;
  height: 40px;
}

.register-footer {
  margin-top: 15px;
  text-align: center;
  font-size: 13px;
  color: #666;
}

.register-footer p {
  margin: 0;
}

.input-icon {
  color: #999;
  margin-right: 6px;
  font-size: 16px;
}

/* 响应式调整 */
@media (min-width: 480px) {
  .form-grid {
    grid-template-columns: 1fr 1fr;
  }

  .form-item:nth-last-child(-n+2) {
    grid-column: span 2;
  }
}

@media (max-width: 480px) {
  .register-box {
    padding: 20px;
  }

  .register-header h1 {
    font-size: 18px;
  }
}
</style>
